﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using GBits.ContactUtilites;

namespace GBits.ContactManager
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            frmHelp.GetForm().MdiParent = this;
        }

        #region File Menu

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog.InitialDirectory = UserOptions.dataDirectory;
            if (OpenFileDialog.ShowDialog() == DialogResult.OK)
            {
                frmContact frm = new frmContact(OpenFileDialog.FileName);
                frm.MdiParent = this;
                frm.Show();
            }
        }

        private void newContactToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmContact newContact = new frmContact();
            newContact.MdiParent = this;
            newContact.Show();
        }

        #endregion

        #region Edit Menu

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmSettings set = new frmSettings();
            if (set.ShowDialog() == DialogResult.OK)
            {
                this.tvContacts.Dock = UserOptions.treeDock;
                this.tsMain.Visible = UserOptions.toolbarVisible;
                this.ucEvents1.Dock = UserOptions.eventDock;
            }
        }

        #endregion

        #region View Menu

        private void restoreCurrentToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.ActiveMdiChild is frmContact)
            {
                this.ActiveMdiChild.WindowState = FormWindowState.Normal;
                ((frmContact)this.ActiveMdiChild).RestoreSize();
            }
        }

        private void eventPlannerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmEvents frm = frmEvents.GetForm();
            frm.MdiParent = this;
            frm.Show();
        }


        private void searchContactsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmSearchContacts frm = frmSearchContacts.GetForm();
            frm.MdiParent = this;
            frm.Show();
        }

        #endregion

        #region Window Menu

        private void arrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(System.Windows.Forms.MdiLayout.ArrangeIcons);
        }

        private void cascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(System.Windows.Forms.MdiLayout.Cascade);
        }

        private void arrangeHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(System.Windows.Forms.MdiLayout.TileHorizontal);
        }

        private void aToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(System.Windows.Forms.MdiLayout.TileVertical);
        }

        private void maximizeAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form[] charr = this.MdiChildren;

            foreach (Form chform in charr)
                if (chform is frmContact)
                {
                    chform.WindowState = FormWindowState.Maximized;
                }
        }

        private void minimizeAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form[] charr = this.MdiChildren;

            foreach (Form chform in charr)
                if (chform is frmContact)
                {
                    chform.WindowState = FormWindowState.Minimized;
                }
        }

        private void restoreToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form[] charr = this.MdiChildren;

            foreach (Form chform in charr)
                if (chform is frmContact)
                {
                    this.ActiveMdiChild.WindowState = FormWindowState.Normal;
                    ((frmContact)chform).RestoreSize();
                }
        }

        #endregion

        #region Help Menu

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmAbout abt = new frmAbout();
            abt.ShowDialog();
        }

        private void localHelpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmHelp help = frmHelp.GetForm();
            help.MdiParent = this;
            help.Dock = UserOptions.helpDock;
            help.Show();
        }

        private void externalHelpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start("http://code.google.com/p/gbits-contactmanager/wiki/MainPage");
            }
            catch
            {
                MessageBox.Show("Error opening browser", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        private void frmMain_Load(object sender, EventArgs e)
        {
            ucEvents1.setButtons(false);
            populateTree();
            DataAccess.GetData().GetOptions();
            tvContacts.Dock = UserOptions.treeDock;
            frmHelp.GetForm().Dock = UserOptions.helpDock;
            tsMain.Visible = UserOptions.toolbarVisible;
            ucEvents1.Dock = UserOptions.eventDock;
        }

        public void populateTree()
        {
            tvContacts.Nodes.Clear();
            DataTable contacts = DataAccess.GetData().GetTreeContactList();
            TreeNode root = new TreeNode("Contact Manager");

            for (int i = 0; i < contacts.Rows.Count; i++)
            {
                bool found = false;
                foreach (TreeNode node in root.Nodes)
                {
                    if (node.Text == contacts.Rows[i][2].ToString())
                    {
                        found = true;
                        TreeNode tn = new TreeNode(contacts.Rows[i][1].ToString());
                        tn.Tag = new TagCode(contacts.Rows[i][2].ToString(), contacts.Rows[i][1].ToString(), contacts.Rows[i][0].ToString());
                        node.Nodes.Add(tn);
                        break;
                    }
                }
                if (!found)
                {
                    TreeNode org = new TreeNode(contacts.Rows[i][2].ToString());
                    org.Tag = new TagCode("Organization", contacts.Rows[i][2].ToString(), String.Empty);
                    TreeNode tn = new TreeNode(contacts.Rows[i][1].ToString());
                    tn.Tag = new TagCode(contacts.Rows[i][2].ToString(), contacts.Rows[i][1].ToString(), contacts.Rows[i][0].ToString());
                    org.Nodes.Add(tn);
                    root.Nodes.Add(org);
                }
            }
            tvContacts.Nodes.Add(root);
        }

        internal class TagCode
        {
            internal string NodeType { get; set; }
            internal string Name { get; set; }
            internal string Id { get; set; }
            internal TagCode(string nodeType, string name, string id)
            {
                Id = id.ToUpper();
                Name = name;
                NodeType = nodeType;
            }
        }

        private void eventBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (eventBarToolStripMenuItem.Checked)
            {
                eventBarToolStripMenuItem.Checked = false;
                ucEvents1.Visible = false;
            }
            else
            {
                eventBarToolStripMenuItem.Checked = true;
                ucEvents1.Visible = true;
            }
        }

        private void contactListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (contactListToolStripMenuItem.Checked)
            {
                contactListToolStripMenuItem.Checked = false;
                tvContacts.Visible = false;
            }
            else
            {
                contactListToolStripMenuItem.Checked = true;
                tvContacts.Visible = true;
            }
        }

        private void tvContacts_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Right)
                {
                    TreeNode selNode = tvContacts.GetNodeAt(e.Location);
                    tvContacts.SelectedNode = selNode;
                    if (selNode != null)
                    {
                        TagCode tc = (TagCode)selNode.Tag;
                        contextTree_New.Visible = (tc != null);
                        contextTree_Open.Visible = (tc != null && tc.Id != String.Empty);
                        contextTree_Delete.Visible = (tc != null && tc.Id != String.Empty);
                    }
                    ContextMenu.Show(tvContacts,e.Location);
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show("Error Handling Context Menu", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tvContacts_DoubleClick(object sender, EventArgs e)
        {
            TreeNode selNode = tvContacts.SelectedNode;
            if (selNode != null)
            {
                TagCode tc = (TagCode)selNode.Tag;
                if (tc.Id == String.Empty)
                {
                    MyContact c = new MyContact();
                    c.Organization.OrgName = tc.NodeType;
                    frmContact frm = new frmContact(c);
                    frm.MdiParent = this;
                    frm.Show();
                }
                else if(tc.Id != null)
                {
                    try
                    {
                        frmContact frm = new frmContact(tc.Id);
                        frm.MdiParent = this;
                        frm.Show();
                    }
                    catch
                    {
                        frmRemoveCheck.GetForm().ShowDialog();
                        if (frmRemoveCheck.GetForm().DialogResult == DialogResult.OK)
                        {
                            tvContacts.Nodes.Remove(selNode);
                            if (selNode.Parent.Nodes.Count < 1)
                                tvContacts.Nodes.Remove(selNode.Parent);
                        }
                    }
                }
            }
        }

        private void contextTree_New_Click(object sender, EventArgs e)
        {
            TreeNode selNode = tvContacts.SelectedNode;
            if (selNode != null)
            {
                TagCode tc = (TagCode)selNode.Tag;
                if (tc.Id == String.Empty)
                {
                    MyContact c = new MyContact();
                    c.Organization.OrgName = tc.NodeType;
                    frmContact frm = new frmContact(c);
                    frm.MdiParent = this;
                    frm.Show();
                }
            }
        }

        private void contextTree_Open_Click(object sender, EventArgs e)
        {
            TreeNode selNode = tvContacts.SelectedNode;
            if (selNode != null)
            {
                try
                {
                    TagCode tc = (TagCode)selNode.Tag;
                    if (tc.Id != String.Empty)
                    {
                        frmContact frm = new frmContact(tc.Id);
                        frm.MdiParent = this;
                        frm.Show();
                    }
                }
                catch
                {
                    frmRemoveCheck.GetForm().ShowDialog();
                    if (frmRemoveCheck.GetForm().DialogResult == DialogResult.OK)
                    {
                        tvContacts.Nodes.Remove(selNode);
                        if (selNode.Parent.Nodes.Count < 1)
                            tvContacts.Nodes.Remove(selNode.Parent);
                    }
                }
            }
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode selNode = tvContacts.SelectedNode;
            if (selNode != null)
            {
                TagCode tc = (TagCode)selNode.Tag;
                try
                {
                    TreeNode rent = selNode.Parent;
                    rent.Nodes.Remove(selNode);
                    if (rent.Nodes.Count < 1)
                    {
                        TreeNode root = rent.Parent;
                        root.Nodes.Remove(rent);
                    }
                    File.Delete(tc.Id);
                }
                catch
                {
                    MessageBox.Show("Error removing contact", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void tvContacts_VisibleChanged(object sender, EventArgs e)
        {
            if (tvContacts.Visible)
            {
                populateTree();
            }
        }


    }
}
